<template>
  <div class="news">
    <div style="display: flex;align-items: center;margin: 6px;">
      <img :src="iconSvg" alt="" style="width: 30px; height: auto;" />
      <div style="flex: 1;width: 0;">
        <div
          style="font-weight: bold;margin-left: 6px;font-size: 1rem;;text-align: left;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">
          {{ newsTypes[newsTypeIndex].title }}
        </div>
      </div>
      <div class="icon" style="width: 20px;margin-right: 2px;" @click.stop="movePrev()">
        <i class="fa-solid fa-chevron-left"></i>
      </div>

      <div class="icon" style="width: 20px;margin-right: 2px;" @click.stop="loadNews()">
        <i :class="['fa-solid', 'fa-rotate-right', { 'fa-spin': loading }]"></i>
      </div>

      <div class="icon" style="width: 20px;" @click.stop="moveNext()">
        <i class="fa-solid fa-chevron-right"></i>
      </div>
    </div>

    <div class="news-content">
      <a-loading v-if="loading"></a-loading>
      <div class="news-list">
        <div v-for="(item, index) in news" :key="index" class="news-item" @click.stop="openUrl(item.url)">
          <img :src="item.img" alt="" class="img" @error="handleImgError($event)" />
          <div class="news-text">
            <template v-if="newsTypeIndex === 0">
              <span
                style="display: -webkit-box;-webkit-line-clamp: 2; -webkit-box-orient: vertical;overflow: hidden;text-overflow: ellipsis;word-break: break-all;">
                {{ item.title }}
              </span>
              <span v-if="item.date" style="color: #999;font-size: 12px;">发布日期：{{ item.date }}</span>
            </template>
            <template v-else>
              <span>
                {{ item.title }}
              </span>
              <span class="tip" v-if="item.desc"
                :class="{ error: item.desc.indexOf('热') >= 0, warn: item.desc.indexOf('新') >= 0 }">{{
                  item.desc }}</span>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "a-news",
}
</script>
<script setup>
import iconSvg from '/public/assets/app-logo/news.svg';
import defaultSvg from '/public/assets/img/default.svg';
import baiduApi from '@/api/baidu_api.js';
import touTiaoApi from '@/api/toutiao_api';
import ALoading from "@/components/a-loading.vue";
import { ref, onMounted, onUnmounted, watch } from 'vue';
const newsTypes = ref([{
  name: 'awy',
  title: '公司动态',
}, {
  name: 'baidu',
  title: '百度热搜',
}, {
  name: 'toutiao',
  title: '头条热搜',
}]);
const newsTypeIndex = ref(0);
const loading = ref(true);
const news = ref([]);

const handleImgError = (event) => {
  event.target.src = defaultSvg; // 设置为默认图片
};
const movePrev = () => {
  if (newsTypeIndex.value > 0) {
    newsTypeIndex.value--;
  } else {
    newsTypeIndex.value = newsTypes.value.length - 1;
  }
  loadNews();
}
const moveNext = () => {
  if (newsTypeIndex.value < newsTypes.value.length - 1) {
    newsTypeIndex.value++;
  } else {
    newsTypeIndex.value = 0;
  }
  loadNews();
}
const openUrl = (url) => {
  window.open(url, '_blank');
}
// 加载百度新闻数据
async function loadBaiduNews() {
  loading.value = true;
  news.value = [];
  try {
    const html = await new Promise((resolve) => baiduApi.board(resolve));
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    const container = doc.querySelector('main');

    for (let i = 0; i < container.children[1].children[0].children[1].children.length && i < 20; i++) {
      const item = container.children[1].children[0].children[1].children[i];
      news.value.push({
        title: item.querySelector('.c-single-text-ellipsis').textContent,
        desc: item.querySelector('.c-text').textContent.trim(),
        img: item.querySelector('a img').src,
        url: item.querySelector('a').href
      });
    }
  } finally {
    loading.value = false;
  }
}

// 加载头条新闻数据
async function loadTouTiaoNews() {
  loading.value = true;
  news.value = [];
  try {
    const result = await new Promise((resolve) => touTiaoApi.hot(resolve));
    for (let i = 0; i < result.data.length && i < 20; i++) {
      const element = result.data[i];
      news.value.push({
        title: element.Title,
        desc: element.LabelDesc,
        img: element.Image.url,
        url: element.Url
      });
    }
  } finally {
    loading.value = false;
  }
}
// 加载公司新闻数据
async function loadAwyNews() {
  loading.value = true;
  news.value = [];
  try {
    // 通过插件消息机制请求background抓取
    const res = await new Promise((resolve) => {
      chrome.runtime.sendMessage({ action: "fetchAwyNews" }, resolve);
    });
    if (!res || !res.html) {
      loading.value = false;
      return;
    }
    const parser = new DOMParser();
    const doc = parser.parseFromString(res.html, 'text/html');
    const items = doc.querySelectorAll('.entrenews-list-views ul li');
    for (let i = 0; i < items.length && i < 20; i++) {
      const item = items[i];
      const imgElement = item.querySelector('img');
      if (!item.querySelector('.word h2')) {
        continue;
      }
      news.value.push({
        title: item.querySelector('.word h2').textContent,
        desc: '',
        date: item.querySelector('.word p').textContent,
        img: imgElement ? imgElement.src : defaultSvg,
        url: 'https://www.ava.com.cn' + item.querySelector('a').getAttribute('href')
      });
    }
  } catch (e) {
    console.log('加载公司新闻失败:', e);
  } finally {
    loading.value = false;
  }
}

// 主函数调用
async function loadNews() {
  if (newsTypeIndex.value === 0) {
    await loadAwyNews();
  } if (newsTypeIndex.value === 1) {
    await loadBaiduNews();
  } else if (newsTypeIndex.value === 2) {
    await loadTouTiaoNews();
  }
}
onMounted(async () => {
  loadNews();
})

</script>

<style scoped lang="less">
@import './news.less';
</style>